package com.marion.codestandard.demo008;

import com.marion.codestandard.demo008.dto.UserDTO;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

import java.util.concurrent.TimeUnit;

/**
 * 原型模式创建对象
 * 1. 轻量级对象new效率高于原型模式
 * @author Marion
 * @date 2022/5/13 16:16
 */
public class Demo008 {

    @Benchmark
    @BenchmarkMode(Mode.AverageTime)
    @Warmup(iterations = 1, timeUnit = TimeUnit.SECONDS)
    @Measurement(iterations = 1, time = 5, timeUnit = TimeUnit.SECONDS)
    @OutputTimeUnit(TimeUnit.SECONDS)
    @Fork(1)
    @Threads(1)
    public static void newUserDTO() {
        long start = System.currentTimeMillis();
        for (int i = 0; i < 10000000; i++) {
            UserDTO userDTO = new UserDTO(1, "张三");
            userDTO.setName("张三");
        }
        long end = System.currentTimeMillis();
        System.out.println("newUserDTO="  + (end -start) + "ms");
    }

    @Benchmark
    @BenchmarkMode(Mode.AverageTime)
    @Warmup(iterations = 1, timeUnit = TimeUnit.SECONDS)
    @Measurement(iterations = 1, time = 5, timeUnit = TimeUnit.SECONDS)
    @OutputTimeUnit(TimeUnit.SECONDS)
    @Fork(1)
    @Threads(1)
    public static void cloneUserDTO() {
        long start = System.currentTimeMillis();
        UserDTO userDTO = new UserDTO(1, "张三");
        for (int i = 0; i < 10000000; i++) {
            UserDTO clone =  (UserDTO) userDTO.clone();
            clone.setName("李四");
        }
        long end = System.currentTimeMillis();
        System.out.println("cloneUserDTO="  + (end -start) + "ms");
    }

    public static void main(String[] args) throws RunnerException {
        OptionsBuilder builder = new OptionsBuilder();
        Options build = builder.include(Demo008.class.getSimpleName())
                .forks(1)
                .build();
        new Runner(build).run();
    }

}
